package com.csjbot.snowbotagingtest;

import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.csjbot.csjbase.base.CsjBaseActivity;
import com.csjbot.csjbase.log.Csjlogger;
import com.csjbot.snowbot_rogue.camera.CameraInterface;
import com.csjbot.snowbot_rogue.platform.SnowBotManager;
import com.csjbot.snowbot_rogue.services.BackgroundPlayService;
import com.csjbot.snowbot_rogue.services.RogueBGService;
import com.csjbot.snowbot_rogue.utils.Constant;
import com.csjbot.snowbot_rogue.utils.WeakReferenceHandler;
import com.slamtec.slamware.robot.Pose;

import net.steamcrafted.loadtoast.LoadToast;

import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static dou.utils.FileUtil.createFolder;

public class MainActivity extends CsjBaseActivity {

    @BindView(R.id.testSerial1)
    Button testSerial1;
    @BindView(R.id.show_serial_2)
    TextView showSerial2;
    @BindView(R.id.hw_ScrollView1)
    ScrollView hwScrollView1;
    @BindView(R.id.testEnd)
    Button testEnd;
    @BindView(R.id.surfaceview)
    SurfaceView mSurfaceView;
    @BindView(R.id.activity_hardware_test)
    LinearLayout activityHardwareTest;

    private Camera mCamera;
    private SurfaceHolder mSurfaceHolder;
    private MediaRecorder mediaRecorder;
    private String currentFileName = "";
    private MainActivityHandler mHandler = new MainActivityHandler(this);
    private boolean mIsRecording = false;
    private LoadToast loadToast = null;
    private int recordTime = 0;
    private SnowBotManager snowBotManager = SnowBotManager.getInstance();
    private Intent rogueBGServiceIntent, backgroundPlayService;

    private boolean isAutoRunning;

    private Runnable recordRunnable = new Runnable() {
        @Override
        public void run() {
            recordTime++;
            loadToast.setText(String.format(Locale.getDefault(), "%02d : %02d", recordTime / 60, recordTime % 60));
            mHandler.postDelayed(this, 1000);
        }
    };

    private class MainActivityHandler extends WeakReferenceHandler<MainActivity> {
        public MainActivityHandler(MainActivity reference) {
            super(reference);
        }

        @Override
        protected void handleMessage(MainActivity reference, Message msg) {

        }
    }


    @Override
    public void afterViewCreated(Bundle savedInstanceState) {
        isAutoRunning = true;
        startServices();
//        startCamera();
        startAutoRunning();
//        startPartol();
    }

    private void startPartol() {
        Pose[] poses = new Pose[]{
                new Pose(1f, 1f, 0f, 0f, 0f, 0f),
                new Pose(-1f, 1f, 0f, 0f, 0f, 0f),
                new Pose(1f, -1f, 0f, 0f, 0f, 0f),
                new Pose(-1f, -1f, 0f, 0f, 0f, 0f),
        };

        snowBotManager.partol(Arrays.asList(poses));
    }

    private void startAutoRunning() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isAutoRunning) {
                    snowBotManager.swingLeftArm((byte)1);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {

                        }
                    });
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    snowBotManager.swingRightArm((byte)1);

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    snowBotManager.swingDoubleArm((byte)1);

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    private void startCamera() {
        mSurfaceHolder = mSurfaceView.getHolder();
        loadToast = new LoadToast(this);
        loadToast.setText("录制中");

        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
//                releaseCamera();
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                initpreview();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }
        });
    }

    private void startServices() {
        rogueBGServiceIntent = new Intent(this, RogueBGService.class);
        backgroundPlayService = new Intent(this, BackgroundPlayService.class);
        startService(backgroundPlayService);
        startService(rogueBGServiceIntent);
    }

    private void initpreview() {
        mCamera = CameraInterface.getInstance().getCameraDevice();
        if (mCamera != null) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    startmediaRecorder();
                }
            }, 5000);
        } else {
            loadToast.setText("摄像机打开错误");
            loadToast.show();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadToast.error();
                }
            }, 1000);
        }

    }

    private void startmediaRecorder() {
        mCamera.unlock();

        if (mediaRecorder == null) {
            Csjlogger.debug("initVideoRecord");
            mIsRecording = true;

            CamcorderProfile mProfile = CamcorderProfile.get(CameraInterface.getInstance().getCameraId()
                    , CamcorderProfile.QUALITY_480P);

            //1st. Initial state
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setCamera(mCamera);

            //2st. Initialized state

            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

            //3st. config
            mediaRecorder.setOutputFormat(mProfile.fileFormat);
            mediaRecorder.setAudioEncoder(mProfile.audioCodec);
            mediaRecorder.setVideoEncoder(mProfile.videoCodec);
            mediaRecorder.setOutputFile(getName());
            mediaRecorder.setVideoSize(640, 480);
//            mediaRecorder.setVideoSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight);
            mediaRecorder.setVideoFrameRate(mProfile.videoFrameRate);
            mediaRecorder.setVideoEncodingBitRate(mProfile.videoBitRate);
            mediaRecorder.setAudioEncodingBitRate(mProfile.audioBitRate);
            mediaRecorder.setAudioChannels(mProfile.audioChannels);
            mediaRecorder.setAudioSamplingRate(mProfile.audioSampleRate);

            mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
        }

        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
        } catch (Exception e) {
            Toast.makeText(this, "fail", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            mIsRecording = true;
            mCamera.lock();
        }

        if (mIsRecording) {
            startRecordHandler();
            loadToast.show();
        }
    }

    private void stopmediaRecorder() {
        if (mediaRecorder != null) {
            if (mIsRecording) {
                try {
                    //下面三个参数必须加，不加的话会奔溃，在mediarecorder.stop();
                    //报错为：RuntimeException:stop failed
                    mediaRecorder.setOnErrorListener(null);
                    mediaRecorder.setOnInfoListener(null);
                    mediaRecorder.setPreviewDisplay(null);
                    mediaRecorder.stop();
                } catch (IllegalStateException e) {
                } catch (RuntimeException e) {
                }
                //mCamera.lock();
                mediaRecorder.reset();
                mediaRecorder.release();
                mediaRecorder = null;
                mIsRecording = false;

                if (mCamera != null) {
                    try {
                        mCamera.reconnect();
                    } catch (IOException e) {
                        Toast.makeText(this, "reconect fail", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                }
                loadToast.success();
                mHandler.removeCallbacks(recordRunnable);
                recordTime = 0;
            }
        }
    }

    @Override
    public void onBackPressed() {
        stopmediaRecorder();
        super.onBackPressed();
    }

    private void startRecordHandler() {
        mHandler.removeCallbacks(recordRunnable);
        mHandler.post(recordRunnable);
    }

    private String getName() {
        createFolder(Constant.SDCARD_VIDEO_PATH);
        // 如 {SDCARD_PATH}/csjbot/video/1472475030.3pg
        currentFileName = Constant.SDCARD_VIDEO_PATH + "testvideo";
        String fileName = currentFileName + ".3gp";
        return fileName;
    }

    @Override
    public void setListener() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_hardware_test;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.testSerial1, R.id.testEnd, R.id.playVideo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.testSerial1:
                break;
            case R.id.testEnd:
                break;
            case R.id.playVideo:
                stopmediaRecorder();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", currentFileName + ".3gp");
                        bundle.putBoolean("loop", false);
                        bundle.putString("title", currentFileName + ".3gp");
                        Intent intent = new Intent(context, VideoPlay.class);
                        intent.putExtra("VIDEODATA", bundle);
                        context.startActivity(intent);
                    }
                }, 3000);
                break;
            default:
                break;
        }
    }


}
